import {alipaySetTitle, alipayGetLocation} from './alipayJsApi'
import Toast from '../components/Toast/index'

const TITLE_LIST = {
  lineQuery: '线路查询',
  Auth: '公交查询',
  lineDetail: '公交查询',
  lineSet: '线路提醒',
  home: '公交查询',
  nearSite: '附近站点',
  lineList: '公交查询',
  linePlan: '线路规划',
  planDetail: '规划详情',
  planSelect: '路线选择',
  myCollect: '我的收藏',
  other: '其它'
}

/**
 * 写入页面标题
 * @params ${path} 当前页面path
 * */
export function setTitle(path) {
  const lineDetailStorage = JSON.parse(localStorage.getItem('lineDetail'))
  const lineListStorage = JSON.parse(localStorage.getItem('lineList'))
  const name = TITLE_LIST[path] ? TITLE_LIST[path] : TITLE_LIST.other
  document.title = name
  alipaySetTitle(name)
  if (path === 'lineDetail') {
    let title = lineDetailStorage.lineName ? `${lineDetailStorage.lineName}路` : `${lineDetailStorage.lineNo}路`
    document.title = title
    alipaySetTitle(title)
  } else if (path === 'lineList') {
    let title = lineListStorage.stopName
    document.title = title
    alipaySetTitle(title)
  }
}

/*
* 设置页面html字体大小
* */
export function setFontSize(width) {
  let html = document.querySelector('html')
  let widthdata = html.offsetWidth
  let fontSize = 100 / width * widthdata
  html.style.fontSize = fontSize + 'px'
  window.addEventListener('resize', function () {
    widthdata = html.offsetWidth
    fontSize = 100 / width * widthdata
    html.style.fontSize = fontSize + 'px'
  })
}

/**
 * 原生跳转
 * @params ${type} replace && href 跳转方式
 * @params url 目标链接
 * */
export function jsLink(type, url) {
  if (type === 'replace') window.location.replace(url)
  else if (type === 'href') window.location.href = url
}

/**
 * 验证空值
 * @params ${data} 需要验证的值
 *
 * 0 为空
 * 1 不为空
 * */
export function checkNull(data) {
  if (data === '' || data === null || data === undefined) return 0
  else return 1
}

/**
 * 对象值转码
 * @params ${params} 传入需要的对象
 * */
export function enCodeString(params) {
  for (let key in params) {
    params[key] = encodeURIComponent(params[key])
  }
  return params
}

/**
 * Toast
 * @params ${val} 内容
 * */
export function showToast(val) {
  Toast(val)
}


/*
* 写入线路查询历史纪录
* @params ${val} 内容
* */
export function setHistory(val) {
  let stringVal = localStorage.getItem('historyList') || '[]'
  let objVal = JSON.parse(stringVal)
  objVal.forEach((v, i) => {
    if (v.lineId === val.lineId) {
      objVal.splice(i, 1)
    }
  })
  objVal.unshift(val)
  if (objVal.length > 10) {
    objVal.pop()
  }
  localStorage.setItem('historyList', JSON.stringify(objVal))
}

/*
* 写入线路规划历史纪录
* @params ${val} 内容
* */
export function setPlanHistory(val) {
  let stringVal = localStorage.getItem('historyVal') || '[]'
  let objVal = JSON.parse(stringVal)
  objVal.forEach((v, i) => {
    if (v.originVal.txt === val.originVal.txt && v.terminalVal.txt === val.terminalVal.txt) {
      objVal.splice(i, 1)
    }
  })
  objVal.unshift(val)
  if (objVal.length > 5) {
    objVal.pop()
  }
  localStorage.setItem('historyVal', JSON.stringify(objVal))
}

/*
* 获取定位信息
* */
export function getLocation(cb) {
  Toast({message: '定位中...', duration: 1000})
  if (navigator.userAgent.indexOf('AlipayClient') === -1) {
    let map = new AMap.Map('')
    map.plugin('AMap.Geolocation', function () {
      let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 5000
      })
      geolocation.getCurrentPosition()
      AMap.event.addListener(geolocation, 'complete', (data) => {
        cb && cb(data.position.getLng(), data.position.getLat())
      })
      AMap.event.addListener(geolocation, 'error', (data) => {
        Toast({message: '定位失败', duration: 1000})
        cb && cb()
      })
    })
  } else {
    alipayGetLocation({
      bizType: 'didi',
      cb: (data) => {
        if (data.error) {
          Toast({message: data.errorMessage, duration: 1000})
          cb && cb()
        } else {
          cb && cb(data.longitude, data.latitude)
        }
      }
    })
  }
}

/*
* 线路详情页滑动效果
* */
export function banner(num, no) {
  function transitionEnd(dom, callback) {
    if (dom && typeof dom === 'object') {
      dom.addEventListener('webkitTransitionEnd', function () {
        callback && callback()
      })
      dom.addEventListener('transitionEnd', function () {
        callback && callback()
      })
    }
  }

  let width = 0.96
  let imageBox = document.querySelector('.site-list')
  let addTransition = function () {
    imageBox.style.webkitTransition = 'all .1s'
    imageBox.style.transition = 'all .1s'
  }
  let removeTransition = function () {
    imageBox.style.webkitTransition = 'none'
    imageBox.style.transition = 'mone'
  }
  let setTranslateX = function (x) {
    imageBox.style.webkitTransform = 'translateX' + x + 'rem)'
    imageBox.style.transform = 'translateX(' + x + 'rem)'
  }
  let index = 0
  if (no) index = no - 1
  transitionEnd(imageBox, function () {
    if (index >= num - 7) {
      index = num - 7
      removeTransition()
      setTranslateX(-index * width)
    } else if (index <= 0) {
      index = 0
      removeTransition()
      setTranslateX(-index * width)
    }
  })
  let startX = 0
  let moveX = 0
  let distanceX = 0
  let isMove = false
  imageBox.addEventListener('touchstart', function (e) {
    startX = e.touches[0].clientX
  })
  imageBox.addEventListener('touchmove', function (e) {
    isMove = true
    moveX = e.touches[0].clientX
    // 调节移动的快慢
    distanceX = (moveX - startX) / 100
    removeTransition()
    setTranslateX(-index * width + distanceX)
  })
  window.addEventListener('touchend', function (e) {
    let indexnum = Math.ceil(Math.abs(distanceX) / width)
    if (Math.abs(distanceX) > (width / 4) && isMove) {
      if (distanceX > 0) {
        index = index - indexnum * 2
      } else {
        index = index + indexnum * 2
      }
      addTransition()
      setTranslateX(-index * width)
    } else {
      addTransition()
      setTranslateX(-index * width)
    }
    startX = 0
    moveX = 0
    distanceX = 0
    isMove = false
  })
}

/*
* 星期数值转换
* */
export function weekVal(val) {
  let arr = val
  let weekArr = []
  arr.forEach((v, i) => {
    switch (v) {
      case '1':
        weekArr.push('一')
        break
      case '2':
        weekArr.push('二')
        break
      case '3':
        weekArr.push('三')
        break
      case '4':
        weekArr.push('四')
        break
      case '5':
        weekArr.push('五')
        break
      case '6':
        weekArr.push('六')
        break
      case '7':
        weekArr.push('日')
        break
      case '一':
        weekArr.push('1')
        break
      case '二':
        weekArr.push('2')
        break
      case '三':
        weekArr.push('3')
        break
      case '四':
        weekArr.push('4')
        break
      case '五':
        weekArr.push('5')
        break
      case '六':
        weekArr.push('6')
        break
      case '日':
        weekArr.push('7')
        break
    }
  })
  return weekArr
}

/*
* 高德模糊搜索匹配，获取经纬度
* */
export function getPlace(val, cb) {
  AMap.service(['AMap.PlaceSearch'], function () {
    let placeSearch = new AMap.PlaceSearch({
      pageSize: 10,
      pageIndex: 1,
      city: '武汉',
      citylimit: true
    })
    if (val !== undefined && val !== '') {
      placeSearch.search(val, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          let data = result.poiList.pois
          cb(data)
        }
      })
    }
  })
}

/*
* 高德获取线路规划
* */
export function getPlan(params, cb) {
  let transOptions = {
    city: '武汉',
    policy: AMap.TransferPolicy.LEAST_TIME
  }
  let trans = new AMap.Transfer(transOptions)
  if (params.originVal.txt === '我的位置' || params.terminalVal.txt === '我的位置') {
    trans.search(params.originVal.location, params.terminalVal.location, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        cb(result.plans)
      } else {
        Toast({message: '系统繁忙！', duration: 1500})
      }
    })
  } else {
    trans.search([{keyword: params.originVal.txt}, {keyword: params.terminalVal.txt}], function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        cb(result.plans)
      } else {
        Toast({message: '系统繁忙！', duration: 1500})
      }
    })
  }
}

/*
* 根据经纬度，计算两个经纬度之间的距离
* */
export function getDistance(lat1, lng1, lat2, lng2) {
  let radLat1 = lat1 * Math.PI / 180.0;
  let radLat2 = lat2 * Math.PI / 180.0;
  let a = radLat1 - radLat2;
  let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10;
  return s
}

/*
* 获取线路站点内最小数据的索引以及添加其它相关参数
* */
export function indexOfSmallest(arr, busArr) {
  let lowest = 0;
  let bool = true
  arr.forEach((v, i) => {
    if (v.distance < arr[lowest].distance) lowest = i
    if (v.isChoice) bool = false
  })
  if (arr[lowest].distance < 1000) {
    arr[lowest].nearest = true
    if (bool) {
      arr[lowest].isChoice = true
    }
  } else {
    if (bool) {
      arr[3].isChoice = true
    }
  }
  let busNewArr = []
  busArr.forEach((v, i) => {
    busNewArr.push(v.split('|'))
  })
  let Array = []
  arr.forEach((v, i) => {
    busNewArr.forEach((v3, i3) => {
      if (v3[2] === v.stopOrder.toString()) {
        if (v3[3] === "1") {
          v.busArrive = true // 站点有车辆信息，并且已到站
        } else {
          v.busComming = true // 站点有车辆信息，并且未到站
        }
      }
    })
    if (v.isChoice) {
      arr.forEach((v2, i2) => {
        if (i2 < i) {
          arr[i2].isBeforeCurrentChoiceNode = true
        }
      })
      busNewArr.forEach((v4, i4) => {
        let obj = {distance: ""}
        if (i >= v4[2] - 1) {
          obj.distance = i - v4[2] + 1
          obj.busArrive = arr[v4[2] - 1].busArrive
          Array.unshift(obj)
        }
      })
    }
  })
  let commingBusArray = [
    {distance: "未发车"},
    {distance: "未发车"}
  ]
  if (Array.length >= 2) {
    commingBusArray[0].distance = Array[0].distance + '站后'
    commingBusArray[1].distance = Array[1].distance + '站后'
    if (Array[0].distance === 0) {
      if (Array[0].busArrive) {
        commingBusArray[0].distance = '已到站'
      } else {
        commingBusArray[0].distance = '即将到站'
      }
    }
    if (Array[1].distance === 0) {
      if (Array[1].busArrive) {
        commingBusArray[1].distance = '已到站'
      } else {
        commingBusArray[1].distance = '即将到站'
      }
    }
  } else if (Array.length === 1) {
    commingBusArray[0].distance = Array[0].distance + '站后'
    commingBusArray[1].distance = '未发车'
    if (Array[0].distance === 0) {
      if (Array[0].busArrive) {
        commingBusArray[0].distance = '已到站'
      } else {
        commingBusArray[0].distance = '即将到站'
      }
    }
  }
  return commingBusArray
}
